package com.gxuwz.zlc.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

/*    shiro三大对象
       subject：用户
       securityManager：管理所有用户
       Realm：连接数据库
   */
@Configuration
public class ShiroConfig {
    /*第三步创建shiroFilterFactoryBean*/
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("defaultWebSecurityManager") DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        bean.setSecurityManager(defaultWebSecurityManager);
        //添加Shiro内置过滤器
        /*anon：无需认证就可以访问
         * authc：必须认证才能访问
         * 必须拥有记住我功能才能用
         * perms 拥有对某个资源的权限才能访问
         * role：拥有某个角色权限才能访问*/
        Map<String, String> filterChainDefinitionMap = new LinkedHashMap();
        //添加权限,没有授权会跳转到为授权界面
        filterChainDefinitionMap.put("/toStudentPlan","perms[student]");
        filterChainDefinitionMap.put("/user/update","perms[user:update]");
        //filterChainDefinitionMap.put("/toStudentPlan","authc");
        bean.setFilterChainDefinitionMap(filterChainDefinitionMap);
        /*设置登录的请求*/
        bean.setLoginUrl("/toLogin");
        //跳转未授权界面
        bean.setUnauthorizedUrl("/noauth");
        return bean;
    }
    /*第二步 创建securityManager*/
    @Bean(name = "defaultWebSecurityManager")
    public DefaultWebSecurityManager defaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        //关联userRealm
        defaultWebSecurityManager.setRealm(userRealm);
        return defaultWebSecurityManager;
    }
    /*第一步创建realm对象 需要自定义类*/
    @Bean
    public UserRealm userRealm(){
        return new UserRealm();
    }
    //ShiroDialect用来整合shiro与thymeleaf
    @Bean
    public ShiroDialect shiroDialect(){
        return new ShiroDialect();
    }
}
